package com.ciwong.epaper.modules.me.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.TimeoutError;
import com.ciwong.ciwongwrite.widget.CWToast;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.bean.BindPhoneInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.UUID;


/**
 * Created by young on 2016/6/14.
 * bind phone number
 */
public class BindPhoneActivity extends BaseActivity {

    private final String TAG = "nextstep";
    private ViewGroup bind_phone_container, bind_phone_linearconner;
    private TextView hint_tv_bind_phone, waiter_phone, mTvGetVerityCode, err_tips_tv;
    private EditText mEtPhoneNumber, mEtVerityCode, mEtName, edt_captcha_code;
    private Button mBtnConfirm;
    private ImageView iv_captcha_code;
    private LinearLayout waiter_phone_tips_layout;
    private String phoneNumber, id;

    private final int TIPS_GONE = 1;
    private final int ERR_CODE_BIND_SAME_PHONE = 8001;
    private final int ERR_CODE_ERR = 80002;

    private final int ERR_CODE_BIND_OTHER_PHONE = 60001;
    private final int ERR_CODE_RIGIST = 60003;//已注册
    private final int ERR_CODE_UNBIND = 60002;//未绑定手机号


    private final int ERR_CODE_ERR_PHONE_NUMBER = 1200;//未绑定手机号

    private final int MESSAGE_COUNTDOWN = 2;
    private final int JUMP_TO_MAIN = 3;
    private final int JUMP_TO_SETTING = 4;
    private int TEMPLATE;
    private String bindUserPhoneTip;
    private String bindPhoneTip;
    private String userName = "";
    private UserInfoBase userInfoBase;
    private int type;
    private boolean isEditUserName = false;
    private String uuid = UUID.randomUUID().toString();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIPS_GONE:
                    //错误提示w
                    err_tips_tv.setVisibility(View.INVISIBLE);
                    break;
                case MESSAGE_COUNTDOWN:
                    //60秒倒计时
                    countdown();
                    break;
                case ERR_CODE_BIND_OTHER_PHONE:
                    errTips(err_tips_tv, "该手机号已绑定其他账号！");
                    break;
                case ERR_CODE_RIGIST:
                    errTips(err_tips_tv, "该手机号已注册，请直接登录!");
                    break;
                case ERR_CODE_ERR:
                    errTips(err_tips_tv, "验证码不正确，请重新输入!");
                    break;
                case JUMP_TO_MAIN:
                    //跳转到主页
                    Intent inTeIntent = new Intent(LoginToken.ACTION_BIND_PHONE_SUCCESS);
                    sendBroadcast(inTeIntent);

                    EJumpManager.jumpToMain(0, BindPhoneActivity.this);
                    finish();
                    break;
                case JUMP_TO_SETTING:
                    //跳转到设置页面
                    //MeJumpManager.jumpToSetting2(BindPhoneDetailActivity.this,R.string.go_back);
                    finish();
                    break;
                case ERR_CODE_ERR_PHONE_NUMBER:
                    errTips(err_tips_tv, "请输入正确的手机号!");
                    break;
                case ERR_CODE_BIND_SAME_PHONE:
                    //更换手机时，输入的手机与已绑定手机号相同
                    errTips(err_tips_tv, "更换的手机号不能与已绑定的手机号相同!");
                    break;
                case ERR_CODE_UNBIND:
                    errTips(err_tips_tv, "该手机号没有绑定账号!");
                    break;
            }
        }
    };

    private ViewOnClickListener mviewOnClickListener = new ViewOnClickListener(2000) {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_confirm) {
                String verityCode = mEtVerityCode.getText().toString().trim();
                String phonenumber = mEtPhoneNumber.getText().toString();
                String userName = mEtName.getText().toString().trim();
                boolean isOnline = true;
                try {
                    isOnline = NetworkUtils.isOnline();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (isOnline) {
                    if (MeUtil.isMobileNum(phonenumber)) {
                        if (isEditUserName) {
                            if (MeUtil.validateUserName(userName)) {
                                if (!MeUtil.isVerify_code_six(verityCode)) {
                                    //如果不是6位纯数字验证码
                                    mHandler.sendEmptyMessage(ERR_CODE_ERR);
                                } else {
                                    //验证验证码是否正确
                                    validSmsVerityCode(verityCode, phonenumber, userName);
                                }
                            } else {
                                errTips(err_tips_tv, getString(R.string.register_name_hint_fail));
                            }
                        } else {
                            if (!MeUtil.isVerify_code_six(verityCode)) {
                                //如果不是6位纯数字验证码
                                mHandler.sendEmptyMessage(ERR_CODE_ERR);
                            } else {
                                //验证验证码是否正确
                                validSmsVerityCode(verityCode, phonenumber, userName);
                            }
                        }

                    } else {
                        mHandler.sendEmptyMessage(ERR_CODE_ERR_PHONE_NUMBER);
                    }

                } else {
                    errTips(err_tips_tv, getString(R.string.connect_disable));
                }

            } else if (id == R.id.waiter_phone) {
                //拨打客服电话
                MeJumpManager.jumpToCallPhone(0, BindPhoneActivity.this, getString(R.string.service_phone));
            } else if (id == R.id.iv_captcha_code) {
                //图形验证码
                setCaptchaCode(iv_captcha_code);
            } else if (id == R.id.tv_get_verity_code) {
                //绑定手机号下一步
                String phonenumber = mEtPhoneNumber.getText().toString();
                String edtCaptchaCode = edt_captcha_code.getText().toString();
                if (!MeUtil.isMobileNum(phonenumber)) {
                    mHandler.sendEmptyMessage(ERR_CODE_ERR_PHONE_NUMBER);
                } else {
                    if (NetworkUtils.isOnline()) {
                        //判断本地是否有手机号
                        String userPhone = SerializableManager.getInstance().getUserPhone(true);

                        if (phonenumber.equals(userPhone) && TEMPLATE == 4) {
                            //与本地手机号相同谈框处理
                            {//来自于换绑页面
                                mHandler.sendEmptyMessage(ERR_CODE_BIND_SAME_PHONE);
                            }
                        } else {
                            try {
                                getVerityCode(phonenumber, edtCaptchaCode, TEMPLATE);
                            } catch (NullPointerException e) {

                            }
                        }

                    } else {
                        errTips(err_tips_tv, getString(R.string.connect_disable));
                    }
                }
            }
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_bind_phone;
    }

    @Override
    protected void findViews() {
        bind_phone_container = findViewById(R.id.bind_phone_container);
        bind_phone_linearconner = findViewById(R.id.bind_phone_linearconner);
        hint_tv_bind_phone = findViewById(R.id.hint_tv_bind_phone);
        bindUserPhoneTip = getResources().getString(R.string.please_input_user_phone_number);
        bindPhoneTip = getResources().getString(R.string.please_input_phone_number);
        mTvGetVerityCode = findViewById(R.id.tv_get_verity_code);
        mEtPhoneNumber = findViewById(R.id.et_phone_number);
        mEtName = findViewById(R.id.et_name);
        mEtVerityCode = findViewById(R.id.et_verity_code);
        mBtnConfirm = findViewById(R.id.btn_confirm);
        waiter_phone_tips_layout = findViewById(R.id.waiter_phone_tips_layout);
        waiter_phone = findViewById(R.id.waiter_phone);
        err_tips_tv = findViewById(R.id.err_tips_tv);
        edt_captcha_code = findViewById(R.id.edt_captcha_code);
        iv_captcha_code = findViewById(R.id.iv_captcha_code);
    }

    @Override
    protected void initEvent() {
        mEtPhoneNumber.addTextChangedListener(watcher);
        mEtVerityCode.addTextChangedListener(watcher);
        edt_captcha_code.addTextChangedListener(watcher);
        mBtnConfirm.setOnClickListener(mviewOnClickListener);
        waiter_phone.setOnClickListener(mviewOnClickListener);
        mTvGetVerityCode.setOnClickListener(mviewOnClickListener);
        iv_captcha_code.setOnClickListener(mviewOnClickListener);
        bind_phone_container.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftInput(v);
                return false;
            }
        });
        mBtnConfirm.setEnabled(false);
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            validbutton();
        }
    };

    @Override
    protected void init() {
        setValideSource(true);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                if (TEMPLATE == EConstants.Template.TEMPLATE_ONE) {
                    //返回登录页面
                    MeJumpManager.jumpToLogin(BindPhoneActivity.this);
                    //退出登录
                    executeOtherThread(new Runnable() {
                        @Override
                        public void run() {
                            LogOutUtil.logOut(BindPhoneActivity.this);
                        }
                    }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                }
                if (type == SettingActivity.SETING_BACK_RETURN) {
                    //退出系统
                    LogOutUtil.logOut(BindPhoneActivity.this);
                }
                BindPhoneActivity.this.finish();
            }
        });

        controlKeyboardLayout(bind_phone_container, mBtnConfirm);
    }


    @Override
    protected void loadData() {
        isEditUserName = false;
        Intent intent = getIntent();
        phoneNumber = intent.getStringExtra(IntentFlag.INTENT_FLAG_STR);
        id = intent.getStringExtra(IntentFlag.INTENT_FLAG_ID);
        type = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, 0);
        setCaptchaCode(iv_captcha_code);
        if (null != getUserInfoBase()) {
            userName = getUserInfoBase().getRealName();
        }
        //根据不同来源设置不同的TITLE
        if ("1".equals(id)) {
            //验证手机号
            setTitleText("验证手机号");
            waiter_phone_tips_layout.setVisibility(View.VISIBLE);
            hint_tv_bind_phone.setText("请输入已绑定的手机号");
            TEMPLATE = EConstants.Template.TEMPLATE_THREE;
        } else if ("2".equals(id)) {
            //绑定手机号
            setTitleText("绑定手机号");
            String bindTip = String.format(bindUserPhoneTip, userName);
            SpannableStringBuilder spanStrNum = new SpannableStringBuilder(bindTip);
            RelativeSizeSpan sizeSpan = new RelativeSizeSpan(2.0f);
            spanStrNum.setSpan(sizeSpan, 0, userName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            hint_tv_bind_phone.setText(spanStrNum);
            TEMPLATE = EConstants.Template.TEMPLATE_ONE;
            if (MeUtil.isNumber(userName)) {
                isEditUserName = true;
            }
        } else if ("3".equals(id)) {
            //注册
            setTitleText("验证手机号");
            hint_tv_bind_phone.setText(R.string.tips_bind_phone);
            TEMPLATE = EConstants.Template.TEMPLATE_TWO;
        } else if ("4".equals(id)) {
            //绑定手机号　来自于换绑　
            setTitleText("更换手机号");
            hint_tv_bind_phone.setText(bindPhoneTip);
            TEMPLATE = EConstants.Template.TEMPLATE_FOUR;
        }
        if (isEditUserName) {
            mEtName.setVisibility(View.VISIBLE);
            mEtName.addTextChangedListener(watcher);
        } else {
            mEtName.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        //如果是来自于强制绑定手机号 则不可返回
        if ("2".equals(id)) {
            //返回登录页面
            MeJumpManager.jumpToLogin(BindPhoneActivity.this);
            //退出登录
            executeOtherThread(new Runnable() {
                @Override
                public void run() {
                    LogOutUtil.logOut(BindPhoneActivity.this);
                }
            }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
            BindPhoneActivity.this.finish();
        } else {
            super.onBackPressed();
        }

    }


    /**
     * the getVerityCode step after click the button
     */
    private void getVerityCode(final String phonenumber, final String captchaCode, final int template) {
        //这个主要是区别类型为４　来自于换绑时　与绑定相同　传１
        int type = template == EConstants.Template.TEMPLATE_FOUR ? EConstants.Template.TEMPLATE_ONE : template;

        //跳转到验证码页面  发送验证码
        boolean isEmpty = phonenumber.isEmpty();
        if (!isEmpty) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(BindPhoneActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            showCricleProgress(null);
            MeDao.getInstance().getSmsVerityCode(EApplication.BRAND_ID + "", phonenumber, uuid, captchaCode, type + "",
                    new BaseCallBack() {
                        @Override
                        public void failed(int errorCode, Object data) {
                            hideCricleProgress();
                            Log.d(TAG, "#######data.toString()#########" + data.toString());
                            Log.d(TAG, "#######errorCode#########" + errorCode);

                            if (errorCode == ERR_CODE_BIND_OTHER_PHONE) {
                                mHandler.sendEmptyMessage(ERR_CODE_BIND_OTHER_PHONE);
                            } else if (errorCode == ERR_CODE_BIND_SAME_PHONE) {
                                mHandler.sendEmptyMessage(ERR_CODE_BIND_SAME_PHONE);
                            } else if (errorCode == ERR_CODE_RIGIST) {
                                mHandler.sendEmptyMessage(ERR_CODE_RIGIST);
                            } else if (errorCode == ERR_CODE_UNBIND) {
                                mHandler.sendEmptyMessage(ERR_CODE_UNBIND);
                            } else {
                                errTips(err_tips_tv, String.valueOf(data));
                            }
                            setCaptchaCode(iv_captcha_code);
                        }

                        @Override
                        public void failed(Object data) {
                            hideCricleProgress();
                            if (data instanceof NoConnectionError) {
                                errTips(err_tips_tv, getString(R.string.connect_disable));
                            } else if (data instanceof TimeoutError) {
                                errTips(err_tips_tv, getString(R.string.connect_timeout));
                            } else {
                                errTips(err_tips_tv, getString(R.string.unknown_error));
                            }
                            setCaptchaCode(iv_captcha_code);
                        }

                        @Override
                        public void success(Object data) {
                            hideCricleProgress();
                            Boolean b = (Boolean) data;
                            if (b) {
                                //来自换绑页面
//								if (template == EConstants.Template.TEMPLATE_FOUR) {
//									BindPhoneActivity.this.finish();
//								}
                                countdown();
                            } else {
                                errTips(err_tips_tv, getString(R.string.unknown_error));
                            }
                        }
                    });
        }

    }


    /**
     * 按钮状态校验
     */
    private void validbutton() {
        String phoneNumber = mEtPhoneNumber.getText().toString().trim();
        String edtCaptchaCode = edt_captcha_code.getText().toString().trim();
        String verityCode = mEtVerityCode.getText().toString().trim();
        String userName = mEtName.getText().toString().trim();
        boolean isHaveCheck = true;
        if (isEditUserName) {
            if (userName.length() >= 2) {
                isHaveCheck = true;
            } else {
                isHaveCheck = false;
            }
        }
        if (phoneNumber != null && verityCode != null && phoneNumber.length() == 11 && verityCode.length() == 6 && isHaveCheck) {
            mBtnConfirm.setEnabled(true);
        } else {
            mBtnConfirm.setEnabled(false);
        }

        if (phoneNumber != null && phoneNumber.length() == 11 && edtCaptchaCode != null && edtCaptchaCode.length() >= 4) {
            mTvGetVerityCode.setTextColor(getResources().getColor(R.color.color_light_green));
        } else {
            mTvGetVerityCode.setTextColor(getResources().getColor(R.color.color_btn_disable));
        }

    }

    /**
     * 控制软键盘布局
     *
     * @param root         最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect rect = new Rect();
                        // 获取root在窗体的可视区域
                        root.getWindowVisibleDisplayFrame(rect);
                        // 获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                        int rootInvisibleHeight = root.getHeight()
                                - rect.bottom;
                        // 若不可视区域高度大于100，则键盘显示
                        if (rootInvisibleHeight > 100) {
                            int[] location = new int[2];
                            // 获取scrollToView在窗体的坐标
                            scrollToView.getLocationInWindow(location);
                            // 计算root滚动高度，使scrollToView在可见区域
                            int srollHeight = (location[1]
                                    + scrollToView.getHeight()) - rect.bottom;
                            Log.e(TAG, "onGlobalLayout: srollHeight==" + srollHeight);
                            if (srollHeight > 0) {
                                root.scrollTo(0, srollHeight);
                            }
                        } else {
                            // 键盘隐藏
                            root.scrollTo(0, 0);
                        }
                    }
                });
    }

    private int currentCount = EConstants.COUNT_COUNTDOWN;

    /**
     * 下发短信按钮倒计时60秒
     */
    private void countdown() {
        if (currentCount > 0) {
            mTvGetVerityCode.setTextColor(Color.parseColor("#b7bdba"));
            mTvGetVerityCode.setText(currentCount + "秒");
            mTvGetVerityCode.setEnabled(false);
            mHandler.removeMessages(MESSAGE_COUNTDOWN);
            mHandler.sendEmptyMessageDelayed(MESSAGE_COUNTDOWN, 1000);
            currentCount -= 1;
        } else {
            currentCount = EConstants.COUNT_COUNTDOWN;
            mTvGetVerityCode.setTextColor(getResources().getColor(R.color.color_light_green));
            mTvGetVerityCode.setText(getResources().getString(R.string.resend_message_again));
            mTvGetVerityCode.setEnabled(true);
        }

    }

    /**
     * 验证验证码是否正确
     *
     * @param verityCode
     * @param phonenumber
     */

    private void validSmsVerityCode(final String verityCode, final String phonenumber, final String realName) {
        MeDao.getInstance().ValidSmsVerityCode(EApplication.BRAND_ID + "", phonenumber, verityCode,
                new BaseExtCallBack(BindPhoneActivity.this) {

                    @Override
                    public void failed(int errorCode, Object data) {
                        if (errorCode == ERR_CODE_BIND_OTHER_PHONE) {
                            mHandler.sendEmptyMessage(ERR_CODE_BIND_OTHER_PHONE);
                        } else if (errorCode == ERR_CODE_ERR) {
                            mHandler.sendEmptyMessage(ERR_CODE_ERR);
                        } else {
                            errTips(err_tips_tv, String.valueOf(data));
                        }
                    }

                    @Override
                    public void failed(Object data) {
                        if (data instanceof NoConnectionError) {
                            errTips(err_tips_tv, getString(R.string.connect_disable));
                        } else if (data instanceof TimeoutError) {
                            errTips(err_tips_tv, getString(R.string.connect_timeout));
                        } else {
                            errTips(err_tips_tv, getString(R.string.unknown_error));
                        }
                    }

                    @Override
                    public void success(Object data) {

                        Boolean b = (Boolean) data;
                        if (b) {
                            //根据不同来源做相应的处理
                            switch (TEMPLATE) {
                                //绑定手机号
                                case EConstants.Template.TEMPLATE_ONE:
                                    BindPhone(verityCode, phonenumber, realName);
                                    break;
                                //注册
                                case EConstants.Template.TEMPLATE_TWO:
                                    EJumpManager.jumpToRegister(R.string.login, BindPhoneActivity.this, verityCode, phonenumber);
                                    break;
                                //忘记密码
                                case EConstants.Template.TEMPLATE_THREE:
                                    MeJumpManager.jumpResetPasswordActivity(BindPhoneActivity.this, R.string.go_back, phonenumber, verityCode);
                                    break;
                                case EConstants.Template.TEMPLATE_FOUR:
                                    BindPhone(verityCode, phonenumber, realName);

                                    break;
                            }
                        }
                    }
                });
    }


    /**
     * 输入验证码下一步
     * 绑定手机号
     */
    private void BindPhone(String verityCode, String phonenumber, String realName) {
        if (NetworkUtils.isOnline()) {
            MeDao.getInstance().BindPhone(CWSys.getSharedLong(EConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "",
                    EApplication.BRAND_ID + "", phonenumber, verityCode, realName,
                    new BaseExtCallBack(BindPhoneActivity.this) {


                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            if (errorCode != 17) {
                                errTips(err_tips_tv, String.valueOf(data));
                            }

                        }

                        @Override
                        public void failed(Object data) {
                            if (data instanceof NoConnectionError) {
                                errTips(err_tips_tv, getString(R.string.connect_disable));
                            } else if (data instanceof TimeoutError) {
                                errTips(err_tips_tv, getString(R.string.connect_timeout));
                            } else {
                                errTips(err_tips_tv, getString(R.string.unknown_error));
                            }
                        }

                        @Override
                        public void success(Object data) {
                            BindPhoneInfo bindPhoneInfo = (BindPhoneInfo) data;
                            try {
                                CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), bindPhoneInfo.getMobile());
                                CWSys.setSerializableObject(EConstants.SHARE_PRE_CURR_BIND_PHONE_INFO, bindPhoneInfo);
                            } catch (Exception e) {
                                e.getStackTrace();
                            }
                            if (TEMPLATE == EConstants.Template.TEMPLATE_FOUR) {
                                errTips(err_tips_tv, "更换手机号成功！");
                                mHandler.sendEmptyMessageDelayed(JUMP_TO_SETTING, 1000);
                            } else if (TEMPLATE == EConstants.Template.TEMPLATE_ONE) {
                                if (bindPhoneInfo != null) {
                                    MeDao.getInstance().getUserPoint(bindPhoneInfo.getUser_id() + "");
                                    if (bindPhoneInfo.getUserName() != null) {
                                        UserInfoBase mUserInfoBase = ((EApplication) getApplication()).getUserInfoBase();
                                        if (mUserInfoBase != null) {
                                            mUserInfoBase.setNickName(bindPhoneInfo.getUserName());
                                            mUserInfoBase.setRealName(bindPhoneInfo.getUserName());
                                            ((EApplication) getApplication()).setUserInfoBase(mUserInfoBase);
                                        }
                                    }
                                }
                                errTips(err_tips_tv, "绑定手机号成功！");

                                mHandler.sendEmptyMessageDelayed(JUMP_TO_MAIN, 1000);
                            }
                        }
                    });
        } else {
            errTips(err_tips_tv, getString(R.string.request_failed));
        }
    }


    private void errTips(final View view, String tips) {
        Log.e(TAG, "errTips: ");
        err_tips_tv.setText(tips);
        err_tips_tv.setVisibility(View.VISIBLE);
        bind_phone_container.scrollTo(0, 0);
        hideKeyboard(mEtPhoneNumber);
        mHandler.sendEmptyMessageDelayed(TIPS_GONE, 3000);
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 设置图形验证码
     */
    private void setCaptchaCode(ImageView iv_captcha_code) {
        uuid = UUID.randomUUID().toString();
        String code_url = "https://eapi.ciwong.com/gateway/v5/service/get_captcha_code_png?uuid=" + uuid;
        try {
            if (!ImageLoader.getInstance().isInited()) {
                ImageLoaderHelper.getInstance().init(getApplicationContext());
            }
            ImageLoader.getInstance().displayImage(code_url, iv_captcha_code,
                    EConstants.getEmptyUriOption(), new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {
                            showToastAlert("加载验证码失败，请检查网络后重试！");
                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
